#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <string.h>

int main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    char buf[4097] = { 0 },sizes[100],name;
    int s, client, bytes_read, j, k, i;
    long size;
    socklen_t opt = sizeof(rem_addr);
    FILE *fp;


    // allocate socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

    // bind socket to port 1 of the first available 
    // local bluetooth adapter
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t) 1;
    bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));

    // put socket into listening mode
    listen(s, 1);

    // accept one connection
    client = accept(s, (struct sockaddr *)&rem_addr, &opt);

    ba2str( &rem_addr.rc_bdaddr, buf );
    fprintf(stderr, "accepted connection from %s\n", buf);
    memset(buf, 0, sizeof(buf));

    read(client, &sizes, 1000);
    size=atol(sizes);
    printf("size: %ld\n", size);
    printf("Save file to: ");
    scanf("%s",&name);
    fp=fopen(&name,"wb");    
    //receving file

    for(i=size;i>=-1000;i-=1000){
	    read(client, buf, 1000);
	    fwrite(buf,sizeof(buf),1,fp);
//	    if(sizeof(buf)<1000)break;
    }

    printf("complete\n");	
    fclose(fp);	
    // close connection
    close(client);
    close(s);
    return 0;
}

